package com.hj.saapp.control.activity.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.hj.saapp.BCDApplication;
import com.hj.saapp.R;
import com.hj.saapp.base.BasePresenter;
import com.hj.saapp.common.event.EventExit;
import com.hj.saapp.common.event.EventLogout;
import com.hj.saapp.common.manager.AppManager;
import com.hj.saapp.common.manager.NetworkManager;
import com.hj.saapp.common.utils.StatusBarUtil;
import com.hj.saapp.control.activity.DefaultDialog;
import com.hj.saapp.control.adapter.CommonAdapter;
import com.hj.saapp.model.Validation.EditTextValidator;
import com.hj.saapp.model.library.PullToRefreshBase;
import com.hj.saapp.model.library.PullToRefreshListView;
import com.hj.saapp.view.BaseView;

import java.io.Serializable;
import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import lib.hj.com.commonlib.bean.BaseBean;
import lib.hj.com.commonlib.utils.OnAsyncHttpResponse;
import lib.hj.com.commonlib.utils.Req;

public class BaseActivity extends FragmentActivity implements DefaultDialog.OnDialogClickListener, OnAsyncHttpResponse {

    public BasePresenter basePresenter;
    public ArrayList mData;
    public PullToRefreshListView queryLv;//类似于listView的控件
    public CommonAdapter adapter;//适配器的父类
    public JsonObject json; //用于jaon解析
    public BaseView baseView;
    public int opration = -1;
    public int pageSize = 10;
    public int pageTotal = 2;
    public boolean isLoad = true;
    public boolean isPulltoLoad = false;
    public EditTextValidator editTextValidator;
    public EditTextValidator editTextValidator2;
    ProgressDialog progressDialog = null;
    public boolean isShowLoading = true;
    public ArrayList<String> rfidS = new ArrayList<>();




    @Override

    protected void onNewIntent(Intent intent) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().setActivity(this);
        baseView = new BaseView(this);
        this.setContentView(baseView);
        editTextValidator = new EditTextValidator(this);
        editTextValidator2 = new EditTextValidator(this);
        basePresenter = getPresenter();
        queryLv = (PullToRefreshListView) findViewById(R.id.queryLv);
        mData = new ArrayList();
        if (queryLv != null) {
            adapter = getAdapter();
            queryLv.setAdapter(adapter);
            queryLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                @Override
                public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                    isPulltoLoad = true;
                    opration = 1;
                    prepareLoadListData();
                }

                @Override
                public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                    isPulltoLoad = false;
                    opration = 1;
                    prepareLoadListData();
                }
            });
            queryLv.setMode(PullToRefreshBase.Mode.DISABLED);
        }
        json = new JsonObject();
        initView();
        initListener();
        initData();
        EventBus.getDefault().register(this);
        StatusBarUtil.myStatusBar(this);

    }

    public void initView() {

    }

    public void initListener() {

    }

    public CommonAdapter getAdapter() {

        return null;
    }

    public int getTitleById() {
        return 0;
    }

    public int getLayoutByid() {
        return 0;
    }

    /**
     * 跳转
     */
    public void changeTo(Class cls) {

        Intent intent = new Intent(this, cls);
        this.startActivity(intent);

    }

    /**
     * 跳转
     */
    public void changeToFinish(Class cls) {

        Intent intent = new Intent(this, cls);
        this.startActivity(intent);
        this.finish();
    }

    /**
     * 跳转
     */
    public void changeToFinishDelay(String msg, Class cls) {

        showPopDialog(msg);
        Intent intent = new Intent(this, cls);
        Message message = new Message();
        message.what = 2;
        message.obj = intent;
        baseHandler.sendMessageDelayed(message, 2000);

    }

    /**
     * 跳转
     */
    public void changeToDelay(String msg, Class cls) {

        showPopDialog(msg);
        Intent intent = new Intent(this, cls);
        Message message = new Message();
        message.what = 4;
        message.obj = intent;
        baseHandler.sendMessageDelayed(message, 2000);

    }

    /**
     * 跳转
     */
    public void changeTo(Class cls, Object data) {

        Intent intent = new Intent(this, cls);
        intent.putExtra("data", (Serializable) data);
        this.startActivity(intent);

    }
    /**
     * 跳转
     */
    public void changeToOther(Class cls, Object data) {

        Intent intent = new Intent(this, cls);
        intent.putExtra("other", (Serializable) data);
        this.startActivity(intent);

    }

    // 获取点击事件
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        //注：回调 3
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isHideInput(view, ev)) {
                HideSoftInput(view.getWindowToken());
                view.clearFocus();

            } else {

            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // 判定是否需要隐藏
    private boolean isHideInput(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top
                    && ev.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    // 隐藏软键盘
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void onPositiveClickListener(String type, String text) {

    }

    @Override
    public void onNegativeClickListener(String type, String text) {

    }

    public void prepareLoadData() {


        if (NetworkManager.getNetworkManager().isNetworkConnected()) {

            if (isShowLoading) {

                baseView.showLoading();
            }

            try {
                getHttpData();

            } catch (Exception e) {

            }

        } else {
            listRefreshComplete();
            if (queryLv != null && mData.size() > 0) {
                baseView.showContent();
            } else {

                if (queryLv != null) {
                    baseView.showEmpty();
                }

            }
            showMessageNoNetWork();
        }

    }


    @Override
    public void onSuccess(BaseBean paramObject) {

        if (this.isFinishing()) {
            return;
        }
        listRefreshComplete();
        baseView.showContent();


    }

    @Override
    public void onFailure(int paramInt, String paramString) {

        if (this.isFinishing()) {
            return;
        }

        if (  mData.size() > 0) {

            baseView.showContent();
            listRefreshComplete();
        } else {
            baseView.showEmpty();

        }

        if (checkSign(paramInt)) {
            if (paramInt > 1000) {

                showPopDialog(paramString);
            }

            return;
        }
        showPopDialog(paramString);


    }

    @Override
    public void offLine(Req req) {



    }

    public void showPopDialog(String tip) {
        if (TextUtils.isEmpty(tip)) {
            return;
        }

        if (baseView != null) {
            Snackbar snackbar = Snackbar
                    .make(baseView, tip, Snackbar.LENGTH_LONG)
                    .setAction(getResources().getString(R.string.snackbar_action_text), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });


            View view = snackbar.getView();
            ((TextView) view.findViewById(R.id.snackbar_text)).setTextColor(getResources().getColor(R.color.sys_white));
            snackbar.show();
        }

    }


    public void showMessageNoNetWork() {
        showPopDialog("无网络连接");
    }

    public void showMessageEmpty(String val) {
        showPopDialog(val + "不能为空");
    }

    public void showMessageError(String val) {
        showPopDialog("请输入正确的" + val);
    }

    public void getHttpData() throws Exception {

    }

    public boolean checkSign(int statusCode) {


        return false;

    }

    public Handler baseHandler = new Handler(Looper.getMainLooper()) {


        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (BaseActivity.this.isFinishing()) {
                        return;
                    }

                    break;
                case 2:
                    Intent intent = (Intent) msg.obj;
                    startActivity(intent);
                    BaseActivity.this.finish();
                    break;
                case 3:
                    BaseActivity.this.finish();
                    break;
                case 4:
                    Intent intent2 = (Intent) msg.obj;
                    startActivity(intent2);
                    break;
            }
        }
    };

    public void initData() {

    }


    @Override
    protected void onResume() {
        super.onResume();
        AppManager.getAppManager().setActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (this.isFinishing())
        {
            return;
        }
        else
        {
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        }
    }

    /**
     * 退出
     *
     * @param event
     */
    public void onEventMainThread(EventExit event) {


        this.finish();
    }

    /**
     * 退出
     *
     * @param event
     */
    public void onEventMainThread(EventLogout event) {


    }

    public void finishOneself() {
        Message message = new Message();
        message.what = 3;
        baseHandler.sendMessageDelayed(message, 1000);
    }

    public void prepareLoadListData() {



        if (NetworkManager.getNetworkManager().isNetworkConnected()) {

            if (NetworkManager.getNetworkManager().isGetHost()) {
                if (mData.size() == 0) {
                    baseView.showLoading();
                }

                try {
                    getListData();
                } catch (Exception e) {

                }
            } else {
                listRefreshComplete();
            }

        } else {
            listRefreshComplete();
            if (queryLv != null && mData.size() > 0) {
                baseView.showContent();
            } else {
                baseView.showEmpty();
            }
            showMessageNoNetWork();

        }


    }

    public void getListData() {


        try {
            getHttpData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void listRefreshComplete() {
        baseHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                if (queryLv != null) {

                    queryLv.onRefreshComplete();
                }

            }
        }, 200);
    }

}